package com.example.healkep;

import static com.example.healkep.LoginActivity.setUser;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.healkep.MainActivity.MainActivity;
import com.example.healkep.utils.GetWeek;
import com.example.healkep.utils.InformationUtils;

import org.json.JSONArray;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NewInformationActivity extends AppCompatActivity {

    private String show;
    private int year;
    private int month;
    private int day;

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public String getShow() {
        return show;
    }

    public void setShow(String show) {
        this.show = show;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_information);
        Spinner birth = findViewById(R.id.sbirth);
        EditText height = findViewById(R.id.sheight1);
        EditText nameEt = findViewById(R.id.name_et);
        EditText weight1 = findViewById(R.id.sweight1);
        EditText weight2 = findViewById(R.id.sweight2);
        EditText ffm = findViewById(R.id.et_ffm);
        EditText muscle = findViewById(R.id.et_muscle);
        EditText protein = findViewById(R.id.et_protein);
        EditText Ucre = findViewById(R.id.et_urce);
        Spinner year = findViewById(R.id.syear);
        Spinner month = findViewById(R.id.smonth);
        Spinner day = findViewById(R.id.sday);
        Spinner num = findViewById(R.id.snum);
        Button add = findViewById(R.id.addinformationnew);
        Button search = findViewById(R.id.searchdfrommysql2);
        EditText txt = findViewById(R.id.searchtxt);
        Spinner disease = findViewById(R.id.diseases);
        String[] disarray = new String[1000];

        String[] births = new String[101];
        int[] tempbirths = new int[101];
        for (int i = 0; i <= 100; i++) {
            tempbirths[i] = 1950 + i;
            births[i] = Integer.toString(tempbirths[i]);
        }
        ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, births);
        birth.setAdapter(adapter1);

        /*String[] heights = getResources().getStringArray(R.array.height);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, heights);
        height.setAdapter(adapter2);

        String[] weights = getResources().getStringArray(R.array.weight);
        ArrayAdapter<String> adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, weights);
        weight1.setAdapter(adapter3);
        weight2.setAdapter(adapter3);*/

        String[] nums = getResources().getStringArray(R.array.nums);
        ArrayAdapter<String> adapter5 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, nums);
        num.setAdapter(adapter5);

        String[] years = new String[100];
        int[] tempyears = new int[100];
        for (int i = 0; i < 100; i++) {
            tempyears[i] = i + 2020;
            years[i] = Integer.toString(tempyears[i]);
        }
        ArrayAdapter<String> adapter4 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, years);
        year.setAdapter(adapter4);

        String[] months = new String[12];
        int[] tempmonths = new int[12];
        for (int i = 0; i < 12; i++) {
            tempmonths[i] = i + 1;
            months[i] = Integer.toString(tempmonths[i]);
        }
        ArrayAdapter<String> adapter6 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, months);
        month.setAdapter(adapter6);

        final Button button = findViewById(R.id.adddisease);
        final TextView textView = findViewById(R.id.show);
        HashMap<String, String> record = new HashMap<>();

        search.setOnClickListener(v -> {
            new Thread(() -> {
                try {
                    String name = txt.getText().toString();
                    String json = "{\n" +
                            "    \"name\":\"" + name + "\"\n" +
                            "}";
                    OkHttpClient clientget = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(LoginActivity.url + "/diseases/get")
                            .post(RequestBody.create(MediaType.parse("application/json"), json))
                            .build();
                    Response response = clientget.newCall(request).execute();
                    String resultget = Objects.requireNonNull(response.body()).string();
                    JSONArray jsonArray = new JSONArray(resultget);
                    for (int j = 0; j < jsonArray.length(); j++) {
                        String temp = jsonArray.getString(j);
                        temp = temp.substring(9);
                        temp = temp.replace("t", "");
                        temp = temp.replace("\\", "");
                        temp = temp.replace("}", "");
                        int len = temp.length();
                        temp = temp.substring(0, len - 1);
                        disarray[j] = temp;
                        record.put(temp, "true");
                    }
                } catch (Exception e) {
                    runOnUiThread(() -> Toast.makeText(NewInformationActivity.this, "获取异常", Toast.LENGTH_SHORT).show());
                }
            }).start();
            ArrayAdapter<String> adapter = new ArrayAdapter<>(NewInformationActivity.this, android.R.layout.simple_spinner_item, disarray);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            disease.setAdapter(adapter);
        });

        try {
            int monthtmp = Integer.parseInt(month.getSelectedItem().toString());
            switch (monthtmp) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    String[] days = new String[31];
                    int[] tempdays = new int[31];
                    for (int i = 0; i < 31; i++) {
                        tempdays[i] = i + 1;
                        days[i] = Integer.toString(tempdays[i]);
                    }
                    ArrayAdapter<String> adapter7 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, days);
                    day.setAdapter(adapter7);
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    String[] days2 = new String[30];
                    int[] tempdays2 = new int[30];
                    for (int i = 0; i < 30; i++) {
                        tempdays2[i] = i + 1;
                        days2[i] = Integer.toString(tempdays2[i]);
                    }
                    ArrayAdapter<String> adapter8 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, days2);
                    day.setAdapter(adapter8);
                    break;
                case 2:
                    int yeartmp = Integer.parseInt(year.getSelectedItem().toString());
                    if ((yeartmp % 4 == 0 && yeartmp % 100 != 0) || yeartmp % 400 == 0) {
                        String[] days3 = new String[29];
                        int[] tempdays3 = new int[29];
                        for (int i = 0; i < 30; i++) {
                            tempdays3[i] = i + 1;
                            days3[i] = Integer.toString(tempdays3[i]);
                        }
                        ArrayAdapter<String> adapter9 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, days3);
                        day.setAdapter(adapter9);
                        break;
                    } else {
                        String[] days4 = new String[28];
                        int[] tempdays4 = new int[28];
                        for (int i = 0; i < 30; i++) {
                            tempdays4[i] = i + 1;
                            days4[i] = Integer.toString(tempdays4[i]);
                        }
                        ArrayAdapter<String> adapter10 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, days4);
                        day.setAdapter(adapter10);
                        break;
                    }
            }
        } catch (Exception e) {
            String[] days = new String[31];
            int[] tempdays = new int[31];
            for (int i = 0; i < 31; i++) {
                tempdays[i] = i + 1;
                days[i] = Integer.toString(tempdays[i]);
            }
            ArrayAdapter<String> adapter7 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, days);
            day.setAdapter(adapter7);
        }

        button.setOnClickListener(v ->
        {
            Toast.makeText(NewInformationActivity.this, getShow(), Toast.LENGTH_SHORT).show();
            if (getShow() == null) {
                if (Objects.equals(record.get(disease.getSelectedItem().toString()), "true")) {//未添加过
                    setShow(disease.getSelectedItem().toString() + ";");
                    record.replace(disease.getSelectedItem().toString(), "false");
                }
            } else {
                if (Objects.equals(record.get(disease.getSelectedItem().toString()), "true")) {//未添加过
                    setShow(getShow() + disease.getSelectedItem().toString() + ";");
                    record.replace(disease.getSelectedItem().toString(), "false");
                }
            }
            Toast.makeText(NewInformationActivity.this, getShow(), Toast.LENGTH_SHORT).show();
            textView.setText(getShow());
        });

        add.setOnClickListener(v ->

        {
            String username = LoginActivity.getUser();
            int age = 2022 - Integer.parseInt(birth.getSelectedItem().toString());
            double h = Double.parseDouble(height.getText().toString());
            double w1 = Double.parseDouble(weight1.getText().toString());
            double bmi = 1.0 * w1 / (((1.0 * h) / 100) * ((1.0 * h) / 100));
            String energy = null;
            String aveenergy = null;
            String enweight = null;
            String lenweight = null;
            if (bmi < 18.5) {
                if (num.getSelectedItem().toString().equals("单胎")) {
                    enweight = "13.0~18.5";
                    lenweight = "0.51(0.44~0.58)";
                } else if (num.getAdapter().toString().equals("双胞胎")) {
                    enweight = null;
                    lenweight = null;
                }
            } else if (bmi >= 18.5 && bmi < 25) {
                if (num.getSelectedItem().toString().equals("单胎")) {
                    enweight = "11.5~16";
                    lenweight = "0.42(0.35~0.50)";
                } else if (num.getAdapter().toString().equals("双胞胎")) {
                    enweight = "17~25";
                    lenweight = null;
                }
            } else if (bmi >= 25 && bmi < 30) {
                if (num.getSelectedItem().toString().equals("单胎")) {
                    enweight = "7~11.5";
                    lenweight = "0.28(0.23~0.3)";
                } else if (num.getAdapter().toString().equals("双胞胎")) {
                    enweight = "14~23";
                    lenweight = null;
                }
            } else if (bmi >= 30) {
                if (num.getSelectedItem().toString().equals("单胎")) {
                    enweight = "5~9";
                    lenweight = "0.22(0.17~0.27)";
                } else if (num.getAdapter().toString().equals("双胞胎")) {
                    enweight = "11~19";
                    lenweight = null;
                }
            }
            setYear(Integer.parseInt(year.getSelectedItem().toString()));
            setMonth(Integer.parseInt(month.getSelectedItem().toString()));
            setDay(Integer.parseInt(day.getSelectedItem().toString()));
            String date1 = "" + getYear() + "-" + getMonth() + "-" + getMonth();
            long week = GetWeek.week(date1);
            String json = "{\n" +
                    "    \"username\":\"" + username + "\",\n" +
                    "    \"clientName\":\"" + nameEt.getText().toString() + "\",\n" +
                    "    \"birth\":\"" + birth.getSelectedItem().toString() + "\",\n" +
                    "    \"height1\":\"" + height.getText().toString() + "\",\n" +
                    "    \"weight1\":\"" + weight1.getText().toString() + "\",\n" +
                    "    \"date\":\"" + date1 + "\",\n" +
                    "    \"num\":\"" + num.getSelectedItem().toString() + "\",\n" +
                    "    \"age\":\"" + age + "\",\n" +
                    "    \"energy\":\"" + energy + "\",\n" +
                    "    \"aveenergy\":\"" + aveenergy + "\",\n" +
                    "    \"enweight\":\"" + enweight + "\",\n" +
                    "    \"lenweight\":\"" + lenweight + "\",\n" +
                    "    \"diseases\":\"" + getShow() + "\",\n" +
                    "    \"ffm\":\"" + ffm.getText().toString() + "\",\n" +
                    "    \"muscle\":\"" + muscle.getText().toString() + "\",\n" +
                    "    \"protein\":\"" + protein.getText().toString() + "\",\n" +
                    "    \"ucre\":\"" + Ucre.getText().toString() + "\"\n" +
                    "}";
//            String json2 = "{\n" +
//                    "    \"username\":\"" + username + "\",\n" +
//                    "    \"weight\":\"" + weight2.getText().toString() + "\",\n" +
//                    "    \"date\":\"" + week + "\"\n" +
//                    "}";
            String json2 = "{\n" +
                    "    \"username\":\"" + username + "\",\n" +
                    "    \"weight\":\"" + weight2.getText().toString() + "\",\n" +
                    "    \"date\":\"" + LocalDate.now().toString() + "\"\n" +
                    "}";
            new Thread(() -> {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(LoginActivity.url + "/information/add")
                            .post(RequestBody.create(MediaType.parse("application/json"), json))
                            .build();
                    Response response = client.newCall(request).execute();
                    String result = Objects.requireNonNull(response.body()).string();
                    String[] temp = Objects.requireNonNull(response.header("Set-Cookie")).split(";");
                    String sessionid = temp[0].substring(11);
                    LoginActivity.setSessionID(sessionid);
                    OkHttpClient client2 = new OkHttpClient();
                    Request request2 = new Request.Builder()
                            .url(LoginActivity.url + "/weight/add")
                            .addHeader("Cookie", sessionid)
                            .post(RequestBody.create(MediaType.parse("application/json"), json2))
                            .build();
                    Response response2 = client2.newCall(request2).execute();
                    runOnUiThread(() -> {
                        Toast.makeText(NewInformationActivity.this, "初始化信息成功", Toast.LENGTH_SHORT).show();
                        setUser(username);
                        Intent intent = new Intent();
                        Toast.makeText(NewInformationActivity.this, "登录成功:" + username, Toast.LENGTH_SHORT).show();
                        intent.setClass(NewInformationActivity.this, MainActivity.class);
                        startActivity(intent);
                    });
                } catch (Exception e) {
                    runOnUiThread(() -> Toast.makeText(NewInformationActivity.this, "连接异常", Toast.LENGTH_SHORT).show());
                }
            }).start();
        });
    }
}